import { createStore } from 'redux';
import defaultSettings from '../settings.json';
import { clear, get, getJson, remove, set, setJson } from '@/utils/storage';
import { Role } from '@/api/interface/authentication';
export interface GlobalState {
  settings?: typeof defaultSettings;
  userInfo?: {
    id?: string;
    account?: string;
    email?: string;
    userName?: string;
    avatar?: string;
    menus?: any;
    orgName: string;
    roles?: any;
    token?: string;
  };
  userLoading?: boolean;
  token?: string;
  meuns?: Array<string>;
  actions?: Array<string>;
  roles?: Array<Role>;
  referenceDetails: {
    referenceNumber: string;
    fullName: string;
  };
}

const initialState: GlobalState = {
  settings: defaultSettings,
  userInfo: getJson('userInfo') || {},
  token: get('userToken'),
  meuns: getJson('meuns') || [],
  actions: getJson('actions') || [],
  roles: getJson('roles') || [],
  referenceDetails: getJson('referenceDetails') || '',
};

function rootReducer(state = initialState, action) {
  switch (action.type) {
    case 'update-settings': {
      const { settings } = action.payload;
      return {
        ...state,
        settings,
      };
    }
    case 'update-userInfo': {
      const { userInfo = initialState.userInfo, userLoading } = action.payload;
      setJson('userInfo', userInfo);
      return {
        ...state,
        userLoading,
        userInfo,
      };
    }
    case 'update-token': {
      const { token } = action.payload;
      set('userToken', token);
      return { ...state, token: token };
    }
    case 'update-setting-collapsed': {
      const { collapsed } = action.payload;
      return {
        ...state,
        settings: { ...state.settings, collapsed: collapsed },
      };
    }
    case 'update-meunsAndActions': {
      const { meuns, actions, roles } = action.payload;
      setJson('meuns', meuns);
      setJson('actions', actions);
      setJson('roles', roles);
      return {
        ...state,
        meuns,
        actions,
        roles,
      };
    }
    case 'update-referenceDetails': {
      const { referenceDetails } = action.payload;
      setJson('referenceDetails', referenceDetails);
      return {
        ...state,
        referenceDetails,
      };
    }

    case 'reset': {
      remove('userToken');
      remove('meuns');
      remove('actions');
      remove('roles');
      remove('userInfo');
      return { ...state, token: '', userInfo: { permissions: {} }, meuns: [] };
    }
    default:
      return state;
  }
}

const store = createStore(rootReducer);

export default store;
